<script setup lang="ts">
import type { PopupProps } from 'vant/es'
import closeIconPath from '@/assets/images/icon_close.svg'

defineProps<
  Partial<PopupProps> & {
    title: string
    subTitle?: string
  }
>()
const show = defineModel({ default: false })
const slots: Record<string, any> = useSlots()

function openHandler() {
  window.history.pushState(null, '', '#')
  window.addEventListener('popstate', popHandler)
}

function closeHandler() {
  window.removeEventListener('popstate', popHandler)
}

function goBack() {
  window.history.back()
}

function popHandler() {
  show.value = false
}
</script>

<template>
  <van-popup
    v-model:show="show"
    :round="true"
    v-bind="$attrs"
    position="bottom"
    closeable
    :close-icon="closeIconPath"
    class="drawer"
    @open="openHandler"
    @close="closeHandler"
    @click-overlay="goBack"
    @click-close-icon="goBack"
  >
    <template v-for="(_, name) in slots" :key="name" #[name]>
      <div v-if="name === 'default'">
        <div class="title-container">
          <div class="title-line">
            <h2 class="title">
              {{ title }}
            </h2>
            <slot name="title-tag"></slot>
          </div>
          <div v-if="subTitle" class="sub-title">
            {{ subTitle }}
          </div>
        </div>
        <div class="drawer-content">
          <slot :name="name" />
        </div>
      </div>
      <slot v-else :name="name" />
    </template>
  </van-popup>
</template>

<style scoped lang="scss">
@use "@/assets/css/mixin" as *;

.drawer {
  background: linear-gradient(180deg, #fef1f6 0%, #fefefe 100%);

  > div {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  :deep(.van-popup__close-icon) {
    width: 20px;
    height: 20px;

    > img {
      width: 100%;
      height: 100%;
    }
  }

  .title-container {
    padding: 20px 16px;
    .title-line {
      display: flex;
      align-items: center;
      gap: 4px;
    }
    .title {
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      @include text-overflow;
      @include font-background(
        linear-gradient(90deg, #efd0b3 0%, #f2a880 100%)
      );
    }
    .sub-title {
      margin-top: 8px;
      font-size: 12px;
      font-weight: 400;
      line-height: 16.8px;
      color: #b7987c;
    }
  }

  .drawer-content {
    flex: 1;
    padding: 4px 16px 16px 16px;
    color: #b7987c;
    overflow: auto;
  }
}
</style>
